package world.ztomorrow.gateway.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;


@UtilityClass
@Slf4j
public class JWTUtils {

    private final String secretString = "E66559580A1ADF22L23K302K8D9W348CDD928516062F12E";
    private static final String HEADER_SYSTEM_KEY = "systemKeyHeader";

    /**
     * 创建JWT令牌
     * @return 令牌
     */
    public String createJWT(Long id,  String systemKey) {
        return Jwts.builder()
                .header().add(HEADER_SYSTEM_KEY, systemKey).and()
                .subject(id.toString())
                .signWith(Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString)))
                .compact();
    }

    /**
     * 验证JWT令牌
     * @return 用户ID
     */
    public Long verifyJWT(String token,  String systemKey) {
        try {
            Jws<Claims> claimsJws = Jwts.parser()
                    .verifyWith(Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString)))
                    .build()
                    .parseSignedClaims(token);

            if (Objects.equals(claimsJws.getHeader().get(HEADER_SYSTEM_KEY), systemKey)) {
                return Long.parseLong(claimsJws.getPayload().getSubject());
            }
        } catch (JwtException e) {
            log.warn("JWT解析失败:{}", token);
            log.warn("JWT解析失败:", e);
        }
        return null;
    }
}
